﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Argos.Scheduling;
using System.Configuration;

namespace Argos.Windows.Forms
{
	public partial class ScheduleEditorDialog: Form
	{

		public ScheduleEditorDialog()
		{
			InitializeComponent();

			this.WeeklyEditor.Dock = DockStyle.Fill;
			this.CustomEditor.Dock = DockStyle.Fill;

			this.ScheduleTypeCombo.SelectedIndex = 0;

			this.Size = Settings.Default.FormSize;
		}

		private Schedule _SelectedSchedule;

		public Schedule SelectedSchedule
		{
			get { return _SelectedSchedule; }
			set
			{
				this.WeeklyEditor.Visible = false;
				this.CustomEditor.Visible = false;

				if (value is WeeklySchedule || null == value)
				{
					this.WeeklyEditor.SelectedSchedule = (WeeklySchedule)value;
					this.WeeklyEditor.Visible = true;
					this.ScheduleTypeCombo.SelectedIndex = 0;
				}
				else if (value is CustomSchedule)
				{
					this.CustomEditor.SelectedSchedule = (CustomSchedule)value;
					this.CustomEditor.Visible = true;
					this.ScheduleTypeCombo.SelectedIndex = 1;
				}
				else
				{
					throw new ArgumentException("Unsupported schedule type.");
				}

				_SelectedSchedule = value;
			}
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			base.OnClosing(e);

			if (!e.Cancel && this.WindowState == FormWindowState.Normal)
			{
				Settings.Default.FormSize = this.Size;
				Settings.Default.Save();
			}
		}



		private void OK_Click(object sender, EventArgs e)
		{
			if (this.WeeklyEditor.Visible)
			{
				this.SelectedSchedule = this.WeeklyEditor.SelectedSchedule;
			}
			else if (this.CustomEditor.Visible)
			{
				this.SelectedSchedule = this.CustomEditor.SelectedSchedule;
			}

			this.DialogResult = DialogResult.OK;
			this.Close();
		}

		private void ScheduleTypeCombo_SelectedIndexChanged(object sender, EventArgs e)
		{

			this.WeeklyEditor.Visible = false;
			this.CustomEditor.Visible = false;

			if (this.ScheduleTypeCombo.SelectedIndex == 0)
			{
				this.WeeklyEditor.Visible = true;
			}
			else if (this.ScheduleTypeCombo.SelectedIndex == 1)
			{
				this.CustomEditor.Visible = true;
			}
		}


		private class Settings : ApplicationSettingsBase
		{

			public static Settings Default = (Settings)ApplicationSettingsBase.Synchronized(new Settings());

			[UserScopedSetting]
			[DefaultSettingValue("400,340")]
			public Size FormSize
			{
				get { return (Size)this["FormSize"]; }
				set { this["FormSize"] = value; }
			}

		}

	}
}
